package com.huawei.zyb.taskManager.domain.task.valueobject;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;

/**
 * 任务进度值对象
 * 范围：0-100%，精度：保留两位小数
 */
public final class TaskProgress {
    private static final BigDecimal MIN_PROGRESS = BigDecimal.ZERO;
    private static final BigDecimal MAX_PROGRESS = new BigDecimal("100.00");
    private static final int SCALE = 2;
    
    private final BigDecimal value;

    private TaskProgress(BigDecimal value) {
        this.value = Objects.requireNonNull(value, "任务进度不能为空")
                .setScale(SCALE, RoundingMode.HALF_UP);
        
        if (this.value.compareTo(MIN_PROGRESS) < 0 || this.value.compareTo(MAX_PROGRESS) > 0) {
            throw new IllegalArgumentException("任务进度必须在0-100%之间");
        }
    }

    public static TaskProgress of(BigDecimal value) {
        return new TaskProgress(value);
    }

    public static TaskProgress of(double value) {
        return new TaskProgress(BigDecimal.valueOf(value));
    }

    public static TaskProgress zero() {
        return new TaskProgress(MIN_PROGRESS);
    }

    public static TaskProgress completed() {
        return new TaskProgress(MAX_PROGRESS);
    }

    /**
     * 验证进度与任务状态的一致性
     */
    public void validateWithStatus(TaskStatus status) {
        if (!status.isValidProgress(value.intValue())) {
            throw new IllegalArgumentException(
                String.format("任务状态[%s]与进度[%s%%]不匹配", status.getDescription(), value)
            );
        }
    }

    public BigDecimal getValue() {
        return value;
    }

    public boolean isZero() {
        return value.compareTo(MIN_PROGRESS) == 0;
    }

    public boolean isCompleted() {
        return value.compareTo(MAX_PROGRESS) == 0;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        TaskProgress that = (TaskProgress) obj;
        return Objects.equals(value, that.value);
    }

    @Override
    public int hashCode() {
        return Objects.hash(value);
    }

    @Override
    public String toString() {
        return "TaskProgress{" + value + "%}";
    }
}